import { useState, useEffect } from 'react';

interface UserData {
  id: number;
  name: string;
  age: number;
  email: string;
}

// API配置 - 请根据你的实际后端接口地址进行修改
const API_BASE_URL = 'http://localhost:5000'; // 示例API地址

export default function PythonDemo() {
  const [users, setUsers] = useState<UserData[]>([]);
  const [formData, setFormData] = useState({ name: '', age: '', email: '' });
  const [editingId, setEditingId] = useState<number | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [loading, setLoading] = useState(false);

  // 获取用户列表
  const fetchUsers = async () => {
    try {
      setLoading(true);
      const response = await fetch(API_BASE_URL + '/api/users');
      if (!response.ok) {
        throw new Error('获取用户列表失败');
      }
      const data = await response.json();
      setUsers(data);
    } catch (error) {
      console.error('获取用户列表错误:', error);
      alert('获取用户列表失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    fetchUsers();
  }, []);

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.name || !formData.age || !formData.email) {
      alert('请填写所有字段');
      return;
    }

    try {
      setLoading(true);
      
      if (editingId) {
        // 编辑模式 - 调用更新API
        const response = await fetch(`${API_BASE_URL}/api/update_user/${editingId}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            name: formData.name,
            age: parseInt(formData.age),
            email: formData.email
          }),
        });

        if (!response.ok) {
          throw new Error('更新用户失败');
        }

        const updatedUser = await response.json();
        setUsers(users.map(user => 
          user.id === editingId ? updatedUser : user
        ));
        // 刷新列表
        fetchUsers();

        alert('用户更新成功');
        setEditingId(null);
      } else {
        // 新增模式 - 调用创建API
        const response = await fetch(API_BASE_URL + '/api/add_user', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            name: formData.name,
            age: parseInt(formData.age),
            email: formData.email
          }),
        });

        if (!response.ok) {
          throw new Error('创建用户失败');
        }
        // 创建成功后 刷新用户列表
        fetchUsers();

        alert('用户创建成功');
      }
      
      setFormData({ name: '', age: '', email: '' });
      setShowForm(false);
    } catch (error) {
      console.error('提交表单错误:', error);
      alert(error instanceof Error ? error.message : '操作失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理编辑
  const handleEdit = (user: UserData) => {
    setFormData({ name: user.name, age: user.age.toString(), email: user.email });
    setEditingId(user.id);
    setShowForm(true);
  };

  // 处理删除
  const handleDelete = async (id: number) => {
    if (!confirm('确定要删除这条记录吗？')) {
      return;
    }

    try {
      setLoading(true);
      const response = await fetch(`${API_BASE_URL}/api/delete_user/${id}`, {
        method: 'POST',
      });

      if (!response.ok) {
        throw new Error('删除用户失败');
      }

      setUsers(users.filter(user => user.id !== id));
      alert('用户删除成功');
    } catch (error) {
      console.error('删除用户错误:', error);
      alert(error instanceof Error ? error.message : '删除失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 取消编辑
  const handleCancel = () => {
    setFormData({ name: '', age: '', email: '' });
    setEditingId(null);
    setShowForm(false);
  };

  return (
    <div style={{ maxWidth: '1000px', margin: '0 auto', padding: '20px', fontFamily: 'Arial, sans-serif' }}>
      <h2 style={{ color: '#333', textAlign: 'center', marginBottom: '30px' }}>python学习--用户管理系统</h2>
      
      {/* 操作按钮 */}
      <div style={{ marginBottom: '20px', textAlign: 'right' }}>
        <button 
          onClick={() => setShowForm(true)}
          disabled={loading}
          style={{
            padding: '10px 20px',
            backgroundColor: loading ? '#ccc' : '#1890ff',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: loading ? 'not-allowed' : 'pointer',
            fontSize: '14px'
          }}
        >
          新增用户
        </button>
      </div>

      {/* 加载状态 */}
      {loading && (
        <div style={{ textAlign: 'center', padding: '20px', color: '#666' }}>
          加载中...
        </div>
      )}

      {/* 表单模态框 */}
      {showForm && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0,0,0,0.5)',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          zIndex: 1000
        }}>
          <div style={{
            backgroundColor: 'white',
            padding: '30px',
            borderRadius: '8px',
            width: '400px',
            boxShadow: '0 4px 12px rgba(0,0,0,0.15)'
          }}>
            <h3 style={{ marginBottom: '20px', color: '#333' }}>
              {editingId ? '编辑用户' : '新增用户'}
            </h3>
            <form onSubmit={handleSubmit}>
              <div style={{ marginBottom: '15px' }}>
                <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
                  姓名：
                </label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  style={{
                    width: '100%',
                    padding: '8px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    fontSize: '14px'
                  }}
                  placeholder="请输入姓名"
                />
              </div>
              <div style={{ marginBottom: '15px' }}>
                <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
                  年龄：
                </label>
                <input
                  type="number"
                  value={formData.age}
                  onChange={(e) => setFormData({ ...formData, age: e.target.value })}
                  style={{
                    width: '100%',
                    padding: '8px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    fontSize: '14px'
                  }}
                  placeholder="请输入年龄"
                  min="1"
                  max="120"
                />
              </div>
              <div style={{ marginBottom: '20px' }}>
                <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
                  邮箱：
                </label>
                <input
                  type="email"
                  value={formData.email}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  style={{
                    width: '100%',
                    padding: '8px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    fontSize: '14px'
                  }}
                  placeholder="请输入邮箱"
                />
              </div>
              <div style={{ textAlign: 'right' }}>
                <button
                  type="button"
                  onClick={handleCancel}
                  disabled={loading}
                  style={{
                    padding: '8px 16px',
                    marginRight: '10px',
                    backgroundColor: '#f0f0f0',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    cursor: loading ? 'not-allowed' : 'pointer'
                  }}
                >
                  取消
                </button>
                <button
                  type="submit"
                  disabled={loading}
                  style={{
                    padding: '8px 16px',
                    backgroundColor: loading ? '#ccc' : '#1890ff',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px',
                    cursor: loading ? 'not-allowed' : 'pointer'
                  }}
                >
                  {loading ? '保存中...' : (editingId ? '更新' : '保存')}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* 数据表格 */}
      <div style={{
        backgroundColor: 'white',
        borderRadius: '8px',
        overflow: 'hidden',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
      }}>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ backgroundColor: '#fafafa' }}>
              <th style={{ padding: '12px', textAlign: 'left', borderBottom: '1px solid #f0f0f0', fontWeight: 'bold' }}>
                ID
              </th>
              <th style={{ padding: '12px', textAlign: 'left', borderBottom: '1px solid #f0f0f0', fontWeight: 'bold' }}>
                姓名
              </th>
              <th style={{ padding: '12px', textAlign: 'left', borderBottom: '1px solid #f0f0f0', fontWeight: 'bold' }}>
                年龄
              </th>
              <th style={{ padding: '12px', textAlign: 'left', borderBottom: '1px solid #f0f0f0', fontWeight: 'bold' }}>
                邮箱
              </th>
              <th style={{ padding: '12px', textAlign: 'center', borderBottom: '1px solid #f0f0f0', fontWeight: 'bold' }}>
                操作
              </th>
            </tr>
          </thead>
          <tbody>
            {users.map((user, index) => (
              <tr key={user.id} style={{ backgroundColor: index % 2 === 0 ? '#ffffff' : '#fafafa' }}>
                <td style={{ padding: '12px', borderBottom: '1px solid #f0f0f0' }}>
                  {user.id}
                </td>
                <td style={{ padding: '12px', borderBottom: '1px solid #f0f0f0' }}>
                  {user.name}
                </td>
                <td style={{ padding: '12px', borderBottom: '1px solid #f0f0f0' }}>
                  {user.age}
                </td>
                <td style={{ padding: '12px', borderBottom: '1px solid #f0f0f0' }}>
                  {user.email}
                </td>
                <td style={{ padding: '12px', borderBottom: '1px solid #f0f0f0', textAlign: 'center' }}>
                  <button
                    onClick={() => handleEdit(user)}
                    disabled={loading}
                    style={{
                      padding: '6px 12px',
                      marginRight: '8px',
                      backgroundColor: loading ? '#ccc' : '#52c41a',
                      color: 'white',
                      border: 'none',
                      borderRadius: '4px',
                      cursor: loading ? 'not-allowed' : 'pointer',
                      fontSize: '12px'
                    }}
                  >
                    编辑
                  </button>
                  <button
                    onClick={() => handleDelete(user.id)}
                    disabled={loading}
                    style={{
                      padding: '6px 12px',
                      backgroundColor: loading ? '#ccc' : '#ff4d4f',
                      color: 'white',
                      border: 'none',
                      borderRadius: '4px',
                      cursor: loading ? 'not-allowed' : 'pointer',
                      fontSize: '12px'
                    }}
                  >
                    删除
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        
        {users.length === 0 && !loading && (
          <div style={{ padding: '40px', textAlign: 'center', color: '#999' }}>
            暂无数据，请点击"新增用户"按钮添加数据
          </div>
        )}
      </div>

      {/* 数据统计 */}
      <div style={{ marginTop: '20px', textAlign: 'right', color: '#666' }}>
        共 {users.length} 条记录
      </div>
    </div>
  );
}